import UIKit
import Flutter

/// iOS AppDelegate
/// 
/// 实现Flutter与iOS原生平台的通信
/// 使用MethodChannel处理来自Flutter的方法调用
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    // 获取FlutterViewController
    guard let controller = window?.rootViewController as? FlutterViewController else {
      return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    // 创建MethodChannel，通道名称必须与Flutter端的channelName一致
    let channel = FlutterMethodChannel(
      name: "com.fluttert/native",
      binaryMessenger: controller.binaryMessenger
    )
    
    // 设置方法调用处理器
    channel.setMethodCallHandler { [weak self] (call: FlutterMethodCall, result: @escaping FlutterResult) in
      switch call.method {
      // 获取设备信息
      case "getDeviceInfo":
        let deviceInfo: [String: Any] = [
          "platform": "iOS",
          "version": UIDevice.current.systemVersion,
          "model": UIDevice.current.model,
          "name": UIDevice.current.name
        ]
        result(deviceInfo)
        
      // 显示Toast消息（iOS使用UIAlertController）
      case "showToast":
        let args = call.arguments as? [String: Any]
        let message = args?["message"] as? String ?? ""
        let duration = args?["duration"] as? Int ?? 0
        
        DispatchQueue.main.async {
          let alert = UIAlertController(
            title: nil,
            message: message,
            preferredStyle: .alert
          )
          
          if let controller = self?.window?.rootViewController {
            controller.present(alert, animated: true)
            
            let durationTime = duration == 1 ? 3.0 : 1.5
            DispatchQueue.main.asyncAfter(deadline: .now() + durationTime) {
              alert.dismiss(animated: true)
            }
          }
        }
        result(true)
        
      // 获取电池电量
      case "getBatteryLevel":
        UIDevice.current.isBatteryMonitoringEnabled = true
        let batteryLevel = Int(UIDevice.current.batteryLevel * 100)
        result(batteryLevel)
        
      // 打开系统设置页面
      case "openSettings":
        if let settingsURL = URL(string: UIApplication.openSettingsURLString) {
          if UIApplication.shared.canOpenURL(settingsURL) {
            UIApplication.shared.open(settingsURL)
            result(true)
          } else {
            result(FlutterError(code: "UNAVAILABLE", message: "无法打开设置", details: nil))
          }
        } else {
          result(FlutterError(code: "INVALID_URL", message: "设置URL无效", details: nil))
        }
        
      // 震动设备
      case "vibrate":
        let args = call.arguments as? [String: Any]
        let duration = args?["duration"] as? Int ?? 100
        
        // iOS使用AudioServicesPlaySystemSound实现震动
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)
        result(true)
        
      // 获取应用版本信息
      case "getAppVersion":
        let versionInfo: [String: Any] = [
          "versionName": Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "未知",
          "versionCode": Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "未知"
        ]
        result(versionInfo)
        
      default:
        result(FlutterMethodNotImplemented)
      }
    }
    
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

// 需要导入AudioToolbox框架以支持震动功能
import AudioToolbox

